<template>
  <div v-if="visible" class="modal-overlay" @click="handleOverlayClick">
    <div class="modal">
      <div class="modal-header">
        <div class="modal-title">
          <span>{{ isEditMode ? '编辑项目' : '项目详情' }}</span>
          <span class="project-code">{{ project?.project_code || '' }}</span>
        </div>
        <button class="close-btn" @click="closeModal">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <line x1="18" y1="6" x2="6" y2="18"></line>
            <line x1="6" y1="6" x2="18" y2="18"></line>
          </svg>
        </button>
      </div>

      <div class="modal-content">
        <div class="edit-toggle" :class="{ 'edit-mode': isEditMode }">
          <div class="mode-indicator"></div>
          <span>{{ isEditMode ? '编辑模式' : '查看模式' }}</span>
        </div>

        <form @submit.prevent="handleSave">
          <div class="form-grid">
            <!-- 项目编码 -->
            <div class="form-group">
              <label class="form-label">
                项目编码 <span class="required">*</span>
              </label>
              <input type="text" class="form-input" v-model="formData.project_code" disabled>
            </div>

            <!-- 客户名称 -->
            <div class="form-group">
              <label class="form-label">
                客户名称 <span class="required">*</span>
              </label>
              <input type="text" class="form-input" v-model="formData.customer_name" :readonly="!isEditMode" required
                disabled>
            </div>

            <!-- 客户域名 -->
            <div class="form-group">
              <label class="form-label">
                客户域名 <span class="required">*</span>
              </label>
              <input type="text" class="form-input" v-model="formData.customer_domain" :readonly="!isEditMode" required
                disabled>
            </div>

            <!-- 项目类型 -->
            <div class="form-group">
              <label class="form-label">
                项目类型 <span class="required">*</span>
              </label>
              <div v-if="!isEditMode" class="type-display">
                {{ getProjectTypeText(formData.project_type) }}
              </div>
              <select v-else class="form-select" v-model="formData.project_type" required>
                <option value="SEO">SEO</option>
                <option value="BACKLINK">手动外链</option>
              </select>
            </div>

            <!-- 项目状态 -->
            <div class="form-group">
              <label class="form-label">项目状态</label>
              <div v-if="!isEditMode" class="status-badge" :class="getStatusClass(formData.status)">
                {{ getStatusText(formData.status) }}
              </div>
              <select v-else class="form-select" v-model="formData.status">
                <option value="PENDING">待开始</option>
                <option value="ACTIVE">进行中</option>
                <option value="COMPLETED">已完成</option>
              </select>
            </div>

            <!-- 客户经理 -->
            <div class="form-group">
              <label class="form-label">客户经理</label>
              <input type="text" class="form-input" v-model="formData.customer_manager" :readonly="!isEditMode">
            </div>

            <!-- 开始日期 -->
            <div class="form-group">
              <label class="form-label">开始日期</label>
              <input type="date" class="form-input" v-model="formData.start_date" :readonly="!isEditMode">
            </div>

            <!-- 结束日期 -->
            <div class="form-group">
              <label class="form-label">结束日期</label>
              <input type="date" class="form-input" v-model="formData.end_date" :readonly="!isEditMode">
            </div>

            <!-- 合同金额 -->
            <!-- <div class="form-group">
              <label class="form-label">合同金额</label>
              <input type="number" class="form-input" v-model.number="formData.contract_amount" :readonly="!isEditMode"
                placeholder="请输入合同金额" min="0" step="0.01">
            </div> -->

            <!-- 合同条数 -->
            <div class="form-group">
              <label class="form-label">合同解析条目数</label>
              <input type="number" class="form-input" v-model.number="formData.contract_count" :readonly="!isEditMode"
                placeholder="请输入合同条数" min="1" disabled>
            </div>

            <!-- 合同条款详情 -->
            <div class="form-group full-width">
              <label class="form-label">合同条款详情</label>
              <div class="contract-terms-display">
                <div v-if="formData.contract_terms?.text" class="contract-summary">
                  <strong>合同概要：</strong>{{ formData.contract_terms.text }}
                </div>
                <div v-if="formData.contract_terms?.extra_note" class="contract-note">
                  <strong>备注说明：</strong>{{ formData.contract_terms.extra_note }}
                </div>
                <div v-if="formData.contract_terms?.amount" class="contract-amount">
                  <strong>合同金额：</strong>¥{{ formData.contract_terms.amount }}
                </div>
              </div>
            </div>

            <!-- 合同要求条目 -->
            <div class="form-group full-width">
              <label class="form-label">合同要求条目</label>
              <div class="contract-requirements">
                <div v-if="!formData.contract_requirements || formData.contract_requirements.length === 0"
                  class="no-requirements">
                  暂无合同要求条目
                </div>
                <div v-else class="requirements-list">
                  <div v-for="requirement in formData.contract_requirements" :key="requirement.id"
                    class="requirement-item">
                    <div class="requirement-header">
                      <div class="requirement-type">{{ requirement.requirement_type }}</div>
                      <span class="requirement-status" :class="requirement.status.toLowerCase()">
                        {{ requirement.status === 'PENDING' ? '待处理' : '已完成' }}
                      </span>
                    </div>
                    <div class="requirement-details">
                      <div class="requirement-quantity">
                        <strong>目标数量：</strong>{{ requirement.target_quantity }}条
                      </div>
                      <div class="quality-requirements">
                        <strong>质量要求：</strong>
                        <span v-if="requirement.quality_requirements.da" class="quality-tag">
                          DA ≥ {{ requirement.quality_requirements.da }}
                        </span>
                        <span v-if="requirement.quality_requirements.count" class="quality-tag">
                          需要 {{ requirement.quality_requirements.count }}条
                        </span>
                        <span v-if="requirement.quality_requirements.dofollow !== null" class="quality-tag">
                          {{ requirement.quality_requirements.dofollow ? 'Dofollow' : 'Nofollow' }}
                        </span>
                      </div>
                      <div v-if="requirement.additional_notes" class="requirement-notes">
                        <strong>附加说明：</strong>{{ requirement.additional_notes }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </form>
      </div>

      <div class="modal-actions">
        <button class="btn btn-secondary" @click="closeModal">
          {{ isEditMode ? '取消' : '取消' }}
        </button>
        <button v-if="!isEditMode" class="btn btn-secondary" @click="toggleEditMode">
          编辑
        </button>
        <button v-if="isEditMode" class="btn btn-secondary" @click="cancelEdit">
          取消编辑
        </button>
        <button v-if="isEditMode" class="btn btn-primary" @click="handleSave">
          保存
        </button>
        <button v-if="isEditMode" class="btn btn-danger" @click="handleDelete">
          删除
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import type { Project } from '../types'
import { projectsApi } from '../api/services/projects'

interface Props {
  visible: boolean
  project: Project | null
  mode?: 'view' | 'edit'
}

const props = withDefaults(defineProps<Props>(), {
  mode: 'view'
})

const emit = defineEmits<{
  'update:visible': [visible: boolean]
  'save': [project: Project]
  'delete': [project: Project]
}>()

const isEditMode = ref(props.mode === 'edit')
const formData = ref<any>({
  project_type: 'SEO',
  status: 'PENDING',
  start_date: null,
  end_date: null,
  customer_manager: null,
  contract_amount: undefined,
})

// 监听项目数据变化
watch(() => props.project, (newProject) => {
  if (newProject) {
    formData.value = { ...newProject }
  }
}, { immediate: true })

// 监听模式变化
watch(() => props.mode, (newMode) => {
  isEditMode.value = newMode === 'edit'
})

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'PENDING': '待开始',
    'ACTIVE': '进行中',
    'COMPLETED': '已完成'
  }
  return statusMap[status] || status
}

const getStatusClass = (status: string) => {
  return status
}

const getProjectTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    'SEO': 'SEO优化',
    'BACKLINK_PACKAGE': '外链套餐',
    'BACKLINK_PREPAID': '外链预付费'
  }
  return typeMap[type] || type
}

const closeModal = () => {
  emit('update:visible', false)
  isEditMode.value = props.mode === 'edit'
}

const handleOverlayClick = (e: Event) => {
  if (e.target === e.currentTarget) {
    closeModal()
  }
}

const toggleEditMode = () => {
  isEditMode.value = true
}

const cancelEdit = () => {
  isEditMode.value = false
  // 重置表单数据
  if (props.project) {
    formData.value = { ...props.project }
  }
}

const handleSave = () => {
  if (!formData.value.customer_name || !formData.value.customer_domain) {
    alert('请填写必填字段')
    return
  }

  const updateData = {
    "project_type": formData.value.project_type,
    "status": formData.value.status,
    "start_date": formData.value.start_date,
    "end_date": formData.value.end_date,
    "customer_manager": formData.value.customer_manager,
    "contract_amount": formData.value.contract_amount,
  }
  projectsApi.update(formData.value.id, updateData).then(() => {
    emit('save', formData.value)
    projectsApi.getList()
  })
  isEditMode.value = false
}

const handleDelete = () => {
  if (confirm('确定要删除这个项目吗？')) {
    if (props.project) {
      emit('delete', props.project)
    }
  }
}
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 12px;
  width: 90%;
  max-width: 800px;
  max-height: 90vh;
  overflow: hidden;
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.25);
}

.modal-header {
  padding: 24px 30px;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #f9fafb;
}

.modal-title {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}

.project-code {
  font-family: 'Monaco', 'Menlo', monospace;
  font-size: 12px;
  color: #6b7280;
  background: #e5e7eb;
  padding: 4px 8px;
  border-radius: 4px;
}

.close-btn {
  background: none;
  border: none;
  cursor: pointer;
  padding: 8px;
  border-radius: 6px;
  color: #6b7280;
  transition: all 0.2s;
}

.close-btn:hover {
  background: #f3f4f6;
  color: #374151;
}

.modal-content {
  padding: 30px;
  max-height: 60vh;
  overflow-y: auto;
}

.edit-toggle {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 24px;
  padding: 8px 12px;
  background: #f3f4f6;
  border-radius: 6px;
  font-size: 14px;
  color: #6b7280;
}

.edit-toggle.edit-mode {
  background: #fef3c7;
  color: #92400e;
}

.mode-indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #6b7280;
}

.edit-toggle.edit-mode .mode-indicator {
  background: #f59e0b;
}

.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group.full-width {
  grid-column: 1 / -1;
}

.form-label {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
  margin-bottom: 6px;
}

.required {
  color: #ef4444;
}

.form-input,
.form-select,
.form-textarea {
  padding: 10px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.2s;
}

.form-input:focus,
.form-select:focus,
.form-textarea:focus {
  outline: none;
  border-color: #6366f1;
  box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
}

.form-input:read-only,
.form-textarea:read-only {
  background: #f9fafb;
  color: #6b7280;
}

.type-display {
  padding: 10px 12px;
  background: #f9fafb;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  font-size: 14px;
  color: #374151;
}

.status-badge {
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
  text-align: center;
  display: inline-block;
}

.status-badge.pending {
  background: #fef3c7;
  color: #92400e;
}

.status-badge.active {
  background: #d1fae5;
  color: #065f46;
}

.status-badge.completed {
  background: #dbeafe;
  color: #1e40af;
}

.status-badge.suspended {
  background: #fee2e2;
  color: #dc2626;
}

.modal-actions {
  padding: 20px 30px;
  border-top: 1px solid #e5e7eb;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  background: #f9fafb;
}

.btn {
  padding: 10px 20px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid transparent;
}

.btn-secondary {
  background: white;
  color: #374151;
  border-color: #d1d5db;
}

.btn-secondary:hover {
  background: #f9fafb;
}

.btn-primary {
  background: #6366f1;
  color: white;
}

.btn-primary:hover {
  background: #5b21b6;
}

.btn-danger {
  background: #ef4444;
  color: white;
}

.btn-danger:hover {
  background: #dc2626;
}

/* 合同条款显示样式 */
.contract-terms-display {
  padding: 12px;
  background: #f9fafb;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  font-size: 14px;
}

.contract-summary,
.contract-note,
.contract-amount {
  margin-bottom: 8px;
  line-height: 1.5;
}

.contract-summary:last-child,
.contract-note:last-child,
.contract-amount:last-child {
  margin-bottom: 0;
}

/* 合同要求条目样式 */
.contract-requirements {
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  background: #f9fafb;
}

.no-requirements {
  padding: 20px;
  text-align: center;
  color: #6b7280;
  font-style: italic;
}

.requirements-list {
  padding: 8px;
}

.requirement-item {
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  margin-bottom: 8px;
  padding: 12px;
}

.requirement-item:last-child {
  margin-bottom: 0;
}

.requirement-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.requirement-type {
  font-weight: 600;
  font-size: 14px;
  color: #374151;
}

.requirement-status {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 10px;
  font-weight: 500;
}

.requirement-status.pending {
  background: #fef3c7;
  color: #92400e;
}

.requirement-status.completed {
  background: #d1fae5;
  color: #065f46;
}

.requirement-details {
  font-size: 13px;
  color: #6b7280;
}

.requirement-quantity,
.quality-requirements,
.requirement-notes {
  margin-bottom: 6px;
}

.requirement-quantity:last-child,
.quality-requirements:last-child,
.requirement-notes:last-child {
  margin-bottom: 0;
}

.quality-requirements {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
}

.quality-tag {
  background: #e0e7ff;
  color: #3730a3;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 11px;
  font-weight: 500;
}

@media (max-width: 768px) {
  .modal {
    width: 95%;
    margin: 20px;
  }

  .form-grid {
    grid-template-columns: 1fr;
  }

  .modal-actions {
    flex-direction: column;
  }

  .requirement-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }

  .quality-requirements {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>